package org.jeecg.modules.xl.kuaimai.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.shiro.IgnoreAuth;
import org.jeecg.modules.xl.customer.entity.XlCustomerInfo;
import org.jeecg.modules.xl.kuaimai.KuaimaiAPIConfig;
import org.jeecg.modules.xl.kuaimai.entity.XlKuaimaiStock;
import org.jeecg.modules.xl.kuaimai.service.IXlKmStockService;
import org.jeecg.modules.xl.kuaimai.service.KuaiMaiAPIService;
import org.jeecg.modules.xl.kuaimai.vo.KMStockStatusRespVO;
import org.jeecg.modules.xl.kuaimai.vo.SKUItem;
import org.jeecg.modules.xl.kuaimai.vo.SKUItemListResp;
import org.jeecg.modules.xl.product.entity.XlProductInfo;
import org.jeecg.modules.xl.product.service.IXlProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 特卖相关的接口
 *
 * @author deco
 * @create 2024-11-07
 */
@Api(tags="特卖库存")
@RestController
@RequestMapping("/tm/tmapi")
@Slf4j
public class TMController {

    /**
     * 不分页，因为是直接调用快麦的接口
     * @param kmStockStatusRespVO
     * @param req
     * @return
     * @throws Exception
     */
    @ApiOperation(value="特卖库存查询", notes="特卖库存查询")
        @GetMapping(value = "/stockList")
    public Result<List<KMStockStatusRespVO>> queryListNoPage(KMStockStatusRespVO kmStockStatusRespVO,
                                                       HttpServletRequest req) throws Exception {

        Result result =   new Result< List<KMStockStatusRespVO> >();

        String method = "stock.api.status.query";
        Map<String, String> params = KuaimaiAPIConfig.getKMStockParam("100","1");

        String resultJson = HttpUtil.post("https://gw3.superboss.cc/router", JSON.toJSONString(params));
        //System.out.println("返回结果数据：" + JSON.toJSONString(result));
        KMStockStatusRespVO kmStockStatusResp = JSON.parseObject(resultJson, KMStockStatusRespVO.class);
        int total = kmStockStatusResp.getTotal().intValue();//数据总量
        //计算总页数
        int pageTotal =  (int)Math.ceil( (double)total / 100 );

        List<XlKuaimaiStock> haotemaiStockList = new ArrayList<>();
        //处理第一页
        List<XlKuaimaiStock> firstPageList = kmStockStatusResp.getStockStatusVoList();

        haotemaiStockList.addAll(firstPageList.stream().filter( xlKuaimaiStock ->
                ObjectUtil.isNotEmpty(xlKuaimaiStock.getSuppliernames())&&xlKuaimaiStock.getSuppliernames().contains("广州好特麦")
        ).collect(Collectors.toList()));
        //XlKuaimaiStockMapper xlKuaimaiStockMapper =  SpringContextUtils.getBean(XlKuaimaiStockMapper.class);
        //xlKuaimaiStockMapper.batchInsert(firstPageList);
        Thread.sleep(1000);
        //处理第二页以后
        for(int i = 2;i <= pageTotal; i++){
            log.info("处理第{}页的数据", i);
            //params.put("pageSize","100");
            Map<String, String> paramsTep = KuaimaiAPIConfig.getKMStockParam("100",String.valueOf(i));

            String resultJsonTemp = HttpUtil.post("https://gw3.superboss.cc/router", JSON.toJSONString(paramsTep));

            KMStockStatusRespVO kmStockStatusRespTemp = JSON.parseObject(resultJsonTemp, KMStockStatusRespVO.class);

            //xlKuaimaiStockMapper.batchInsert(kmStockStatusRespTemp.getStockStatusVoList());

            haotemaiStockList.addAll(kmStockStatusRespTemp.getStockStatusVoList().stream().filter( xlKuaimaiStockT ->
                    ObjectUtil.isNotEmpty(xlKuaimaiStockT.getSuppliernames())&&xlKuaimaiStockT.getSuppliernames().contains("广州好特麦")
            ).collect(Collectors.toList()));
        }

        log.info("广州好特麦的库存流水记录有{}条",haotemaiStockList.size());

        result.setResult(haotemaiStockList);

        return result;
    }

    @Autowired
    private KuaiMaiAPIService apiService;

    //使用多线程获取数据
    @ApiOperation(value="特卖库存查询", notes="特卖库存查询")
    @GetMapping(value = "/stockList2")
    public Result<List<KMStockStatusRespVO>> queryListNoPageAsny(KMStockStatusRespVO kmStockStatusRespVO,
                                                             HttpServletRequest req) throws Exception {

        Result result =   new Result< List<KMStockStatusRespVO> >();

        Map<String, String> params = KuaimaiAPIConfig.getKMStockParam("100","1");

        String resultJson = HttpUtil.post("https://gw3.superboss.cc/router", JSON.toJSONString(params));
        //System.out.println("返回结果数据：" + JSON.toJSONString(result));
        KMStockStatusRespVO kmStockStatusResp = JSON.parseObject(resultJson, KMStockStatusRespVO.class);
        int total = kmStockStatusResp.getTotal().intValue();//数据总量
        //计算总页数
        int pageTotal =  (int)Math.ceil( (double)total / 100 );

        List<XlKuaimaiStock> haotemaiStockList = new ArrayList<>();

        //处理第一页
        List<XlKuaimaiStock> firstPageList = kmStockStatusResp.getStockStatusVoList();

//        haotemaiStockList.addAll(firstPageList.stream().filter( xlKuaimaiStock ->
//                ObjectUtil.isNotEmpty(xlKuaimaiStock.getSuppliernames())&&xlKuaimaiStock.getSuppliernames().contains("广州好特麦")
//        ).collect(Collectors.toList()));

        haotemaiStockList.addAll(firstPageList);
        Thread.sleep(1000);

        List<CompletableFuture<List<XlKuaimaiStock> >> asnyResult = new ArrayList<>();

        KuaiMaiAPIService apiService =  SpringContextUtils.getBean(KuaiMaiAPIService.class);
        //使用多线程，处理第二页
        for(int i = 2;i <= pageTotal; i++){
            log.info("处理第{}页的数据", i);
            asnyResult.add(apiService.getStockDataByPageWithAsync("100",String.valueOf(i)));
        }
        //等待所有线程处理完
        for(CompletableFuture<List<XlKuaimaiStock> >  temp : asnyResult){
            List<XlKuaimaiStock>  s = temp.get();
            haotemaiStockList.addAll(s);
        }

        log.info("广州好特麦的库存流水记录有{}条",haotemaiStockList.size());

        result.setResult(haotemaiStockList);

        return result;
    }

    @Autowired
    private IXlKmStockService iXlKmStockService;
    @GetMapping(value = "/listAll")
    public Result<IPage<XlKuaimaiStock>> queryPageList(XlKuaimaiStock xlKuaimaiStock,  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                      @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                        HttpServletRequest req) {
        QueryWrapper<XlKuaimaiStock> queryWrapper = QueryGenerator.initQueryWrapper(xlKuaimaiStock, req.getParameterMap());
        Page<XlKuaimaiStock> page = new Page<XlKuaimaiStock>(pageNo, pageSize);
        IPage<XlKuaimaiStock> pageList = iXlKmStockService.page(page, queryWrapper);
        return Result.OK( pageList);
    }

    @ApiOperation(value="特卖库存查询", notes="特卖库存查询")
    @GetMapping(value = "/flushStock")
    public Result<String> flushStock() throws Exception {
        apiService.flushStock();
        return  Result.ok("库存更新成功");
    }

    @Autowired
    private IXlProductInfoService productInfoService;


    //http://localhost:8058/jeecg-boot//tm/tmapi/getSKUItemList
    @IgnoreAuth
    @GetMapping(value = "/getSKUItemList")
    public Result<String> getSKUItemList() throws Exception {
        Map<String, String> params = KuaimaiAPIConfig.getSKUItemListParam("200","1");
        String resultJson = HttpUtil.post("https://gw3.superboss.cc/router", JSON.toJSONString(params));
        //System.out.println("返回结果数据：" + JSON.toJSONString(result));
        SKUItemListResp skuItemListRespFirst = JSON.parseObject(resultJson, SKUItemListResp.class);
        int total = skuItemListRespFirst.getTotal().intValue();//数据总量
        System.out.println(total);
        //计算总页数
        int pageTotal =  (int)Math.ceil( (double)total / 200 );

        List<SKUItem> resultList = new ArrayList<>(skuItemListRespFirst.getItems()); //第一页

        List<CompletableFuture<List<SKUItem> >> asnyResult = new ArrayList<>();

        KuaiMaiAPIService apiService =  SpringContextUtils.getBean(KuaiMaiAPIService.class);
        //使用多线程，处理第二页
        for(int i = 2;i <= pageTotal; i++){
            log.info("处理第{}页的数据", i);
            asnyResult.add(apiService.getSKUItemListRespWithAsync("200",String.valueOf(i)));
        }
        //等待所有线程处理完
        for(CompletableFuture<List<SKUItem> >  temp : asnyResult){
            List<SKUItem>  s = temp.get();
            resultList.addAll(s);
        }
        Map<String, SKUItem> skuHashMapStream = resultList.stream()
                .collect(Collectors.toMap(SKUItem::getOuterId, i -> i));
        //更新商品主数据
        List<XlProductInfo> productInfoListInDB = productInfoService.list();
        for (XlProductInfo xlProductInfo :productInfoListInDB){
            String upc =  xlProductInfo.getUpcCode();
            SKUItem skuItemTemp  = skuHashMapStream.get(upc);
            if(ObjectUtil.isEmpty(skuItemTemp)){
                continue;
            }
            //更新指定字段
            if(ObjectUtil.isNotEmpty(skuItemTemp.getTitle())){//更新商品描述
                 xlProductInfo.setProductName(skuItemTemp.getTitle());
            }

            if(ObjectUtil.isNotEmpty(skuItemTemp.getTitle())){//更新商品描述
                xlProductInfo.setProductName(skuItemTemp.getTitle());
            }
            //更新商品品牌
            //更新商品类目
            //更新箱规
            if(ObjectUtil.isNotEmpty(skuItemTemp.getBoxnum())){
                xlProductInfo.setCartonSpec(skuItemTemp.getBoxnum().toString());
            }
            //更新产品规格
            //更新重量
            if(ObjectUtil.isNotEmpty(skuItemTemp.getWeight())){
                xlProductInfo.setWeight(skuItemTemp.getWeight());
            }
            //更新进货价
            if(ObjectUtil.isNotEmpty(skuItemTemp.getPurchasePrice())){
                xlProductInfo.setPurchasePrice(skuItemTemp.getPurchasePrice());
            }
            xlProductInfo.setUpdateTime(new Date());
            productInfoService.updateById(xlProductInfo);
        }
        System.out.println(resultList.size());
        return  Result.ok("商品同步成功");
    }


}
